# -*- coding: utf-8 -*-
'''
Created on Jul 11, 2014

@author: LONG HOANG GIANG
'''
import os
import sys
from urlparse import urljoin
# sys.path.append('C:/longhoanggiang/pyLib')
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import lib
import logging
import sqlite3
import json
import workerpool
from lxml import etree

logging.basicConfig(level=logging.DEBUG, format='%(levelname)s :: %(asctime)s :: %(message)s', datefmt='%d/%m/%Y %H:%M:%S')


    
crawlResult = {}

class CrawlJob(workerpool.Job):
    
    def __init__(self, callback, *args):
        self.callback = callback
        self.args = args
        
    def run(self):
        detail, key = self.callback(*self.args)
        global crawlResult
        crawlResult[key] = detail

def createTable(connection):
    cursor = connection.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS udv_content('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'hash' VARCHAR(32), 'name' VARCHAR(200), 'content' BLOB, 'is_header' INTEGER DEFAULT 0)")
    cursor.execute("CREATE INDEX IF NOT EXISTS hash_index ON udv_content(hash)")
    cursor.execute("CREATE INDEX IF NOT EXISTS id_index ON udv_content(id)")
    cursor.close()

cookie = '''JSESSIONID=D06FC847E4598D9FEDD44E6BE17DC0C3; __utma=85239450.915564441.1405095941.1405099434.1405103104.3; __utmc=85239450; __utmz=85239450.1405095941.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmb=85239450.1.10.1405103105'''

class Crawler():
    
    def getDetail(self, url):
        response = lib.Web.load(url, cached=True, cookie=cookie)
        tree = response.build_tree(base_url=url, attr_width='100%')
        nodeContent = tree.xpath("//div[@class='page']//div[@class='middleSecPage']//div[@class='topoicdetails']")[0]
        lib.Etree.cleanNode(".//script", nodeContent)
        lib.Etree.cleanNode(".//p[@align='center']//img[contains(@src, '/images/previous.gif')]/../..", nodeContent)
        lib.Etree.cleanNode(".//div[@class='topicDetailsAdRight']", nodeContent)
        lib.Etree.cleanNodeNextSibling(nodeContent.xpath(".//div[contains(@class, 'AdsBottom')]"), True)
        content = lib.Etree.tostring(nodeContent)
        if type(content).__name__ == 'unicode':
            content = content.encode('utf-8')
        print content
        return content, lib.md5(url)
    
    def getChapters(self, url):
        data = []
        tree = lib.Web.load(url, cached=True).build_tree(base_url=url)
        for node in tree.xpath("//div[@class='topicDetailsShow']/ol/li//a"):
            name = lib.stringify(node).strip("\r").replace("\r", '').strip().replace(u'\xa0', u'')
            if name == u'': continue
            link = urljoin(url, node.get('href'))
            print name
            data.append({'name': name, 'url': link, 'filename': lib.md5(link)})
        return data

    def execute(self, url, databasename=None):
        if databasename == None:
            databasename = raw_input("Enter database name: ")
        path = "/longhoanggiang/database/{0}".format(databasename)
        if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path), 0777)
        connection = sqlite3.connect(path)
        createTable(connection)
        chapters = self.getChapters(url)
        pool = workerpool.WorkerPool(size=10)
         
        for chapter in chapters:
            pool.put(CrawlJob(self.getDetail, chapter['url']))
        pool.shutdown()
        pool.wait()
         
        for chapter in chapters:
            name = chapter['name']
            print type(name).__name__
            detail = crawlResult[lib.md5(chapter['url'])]
            detail = "<h4 id='title'>{0}</h4>{1}".format(name, detail)
            cursor = connection.cursor()
            cursor.execute("INSERT INTO udv_content('name', 'content') VALUES(?, ?)", [unicode(name), buffer(lib.compressStr(json.dumps(detail)))])
            cursor.close()
            print name.decode('iso-8859-1')
            print type(name.decode('iso-8859-1')).__name__
            print detail
             
        connection.commit()
        connection.close()
        logging.info("saved database in {0}".format(path))

if __name__ == '__main__':
    
    c = Crawler()
#     c.getDetail('http://www.roseindia.net/java/beginners/installing_java.shtml')
    c.execute('http://www.roseindia.net/java/beginners/index.shtml', 'javabeginner')
    
    logging.info("Finished")
    os._exit(1)
    